//
//  XHRFileManager.m
//  BuDeJie
//
//  Created by haoran on 16/4/7.
//  Copyright © 2016年 xuhaoran. All rights reserved.
//

#import "XHRFileManager.h"

@implementation XHRFileManager

//删除文件夹下所有文件
+(void)removeDirectoryPath:(NSString *)directoryPath{
    
    NSFileManager * manager = [NSFileManager defaultManager];
    
    //判断输入路径
    BOOL isDirectory ;
    BOOL isExist = [manager fileExistsAtPath:directoryPath isDirectory:&isDirectory];
    
    if (!isExist || !isDirectory) {
        //抛出异常
        NSException * excp = [NSException exceptionWithName:@"fileParhError" reason:@"输入文件路径有误" userInfo:nil] ;
        [excp raise];
    }
    
    NSArray * subPaths = [manager contentsOfDirectoryAtPath:directoryPath error:nil];
    
    for (NSString * subPath in subPaths) {
        
        NSString * filePath = [directoryPath stringByAppendingPathComponent:subPath];
        //删除该路径下的缓存
        [manager removeItemAtPath:filePath error:nil];
    }


}

// 获取文件夹尺寸
+ (NSInteger)getFileSize: (NSString *)directoryPath{
    
    //获取文件管理者
    NSFileManager *manager = [NSFileManager defaultManager];
    
    //判断输入路径
    BOOL isDirectory ;
    BOOL isExist = [manager fileExistsAtPath:directoryPath isDirectory:&isDirectory];
    
    if (!isExist || !isDirectory) {
        //抛出异常
        NSException * excp = [NSException exceptionWithName:@"fileParhError" reason:@"输入文件路径有误" userInfo:nil] ;
        [excp raise];
    }

    
    //获取directoryPath下所有的文件
    NSArray * subPaths = [manager subpathsAtPath:directoryPath];
    NSInteger totalSize = 0;
    //遍历所有文件夹
    for (NSString *subPath in subPaths) {
        //拼接文件全路径
        NSString * filePath = [directoryPath stringByAppendingPathComponent:subPath];
        
        // 排除文件夹
        BOOL isDirectory;
        BOOL isExist = [manager fileExistsAtPath:filePath isDirectory:&isDirectory];
        if (!isExist || isDirectory) continue;
        
        // 排除隐藏文件
        if ([filePath containsString:@".DS"]) continue;
        
        // 指定路径获取这个路径的属性
        // attributesOfItemAtPath:只能获取文件属性
        NSDictionary *attr = [manager attributesOfItemAtPath:filePath error:nil];
        NSInteger size = [attr fileSize];
        
        totalSize += size;
        
    }
    NSLog(@"%zd",totalSize);
    
    return totalSize;
}


@end
